package com.yudean.esb.util;

import org.springframework.beans.factory.annotation.Value;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : DL<duanlei@gdyd.com>
 * @version : 1.0
 */
public class Page<T> {
    private int pageNo = 1;
    private int pageSize;
    private int totalRecord;
    private List<T> results;
    private Map<String, Object> params;
    private boolean autoCalTotalRecord = true;

    public Page() {
        params = new HashMap<String, Object>();
        results = Collections.EMPTY_LIST;
    }

    /**
     * 设置查询参数
     *
     * @param key   在SQL中将使用的参数名称
     * @param param 查询参数
     */
    public void setParameter(String key, Object param) {
        params.put(key, param);
    }

    /**
     * 计算得出总页数（随时更改pageSize都能正确）
     *
     * @return 总页数
     */
    public int getTotalPage() {
        int size = getPageSize();
        int totalPage = totalRecord % size == 0 ? totalRecord / size : (totalRecord / size + 1);
        return totalPage;
    }

    /**
     * 如果Pagesize = 0, 使用config.properties中的默认值
     *
     * @return
     */
    @Value("${page.defaultsize}")
    private String defaultsize;

    public int getPageSize() {
        if (pageSize == 0) {
            if (defaultsize == null || "".equals(defaultsize)) {
                try {
                    pageSize = Integer.parseInt(defaultsize);
                } catch (Exception e) {
                    pageSize = 5000;
                }
            } else {
                pageSize = 5000;
            }
        }
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public Map<String, Object> getParams() {
        return params;
    }

    public Object getParams(String key) {
        return params.get(key);
    }

    public int getPageNo() {
        return pageNo;
    }

    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }

    public int getTotalRecord() {
        return totalRecord;
    }

    public void setTotalRecord(int totalRecord) {
        this.totalRecord = totalRecord;
    }

    public List<T> getResults() {
        return results;
    }

    public void setResults(List<T> results) {
        this.results = results;
    }

    public boolean isAutoCalTotalRecord() {
        return autoCalTotalRecord;
    }

    public void setAutoCalTotalRecord(boolean autoCalTotalRecord) {
        this.autoCalTotalRecord = autoCalTotalRecord;
    }
}